import { type InternalAxiosRequestConfig } from "axios";
import Base64 from "crypto-js/enc-base64";
import hmacSha256 from "crypto-js/hmac-sha256";
import Utf8 from "crypto-js/enc-utf8";
import { MD5 } from "crypto-js";
import { v4 as uuidv4 } from "uuid";

const signature = (
    appkey: string,
    appSecret: string,
    req: InternalAxiosRequestConfig,
) => {
    const method = req.method?.toLocaleUpperCase();
    let URL = req.url;
    if (URL?.includes("?")) {
        let index = URL.indexOf("?");
        let query = URL.slice(index);
        URL = URL.slice(0, index) + decodeURIComponent(query);
    }
    const time = Date.now();
    const nonce = uuidv4();
    const body = req.data;
    let tempBody = "";
    if (body) {
        tempBody = Base64.stringify(MD5(Utf8.parse(JSON.stringify(body))));
    }
    let signStr = `${appkey}\n${method}\n${URL}\n${time}\n${nonce}\n${tempBody}\n`;
    let sign = Base64.stringify(hmacSha256(signStr, appSecret));

    return {
        "x-ca-key": appkey,
        "x-ca-timestamp": time,
        "x-ca-nonce": nonce,
        "x-ca-sign": sign,
    };
};

export default signature;
